<?php

namespace api\controllers;

use common\helpers\ArrayHelper;
use common\helpers\CommonHelper;
use common\models\api\AccessToken;
use services\member\MemberService;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use common\models\member\Attr;
use common\models\member\Member;

/**
 * 需要授权登录访问基类
 *
 * Class OnAuthController
 * @package api\controllers
 * @property yii\db\ActiveRecord|yii\base\Model $modelClass
 */
class OnAuthController extends ActiveController
{
    /**
     * @return array
     */
    public function actions()
    {
//        header('Access-Control-Allow-Origin:*');

        $actions = parent::actions();

        // 注销系统自带的实现方法
        unset($actions['index'], $actions['update'], $actions['create'], $actions['view'], $actions['delete']);

        // 自定义数据indexDataProvider覆盖IndexAction中的prepareDataProvider()方法
        // $actions['index']['prepareDataProvider'] = [$this, 'indexDataProvider'];
        return $actions;
    }

    /**
     * 验证更新是否本人
     *
     * @param $action
     * @return bool
     * @throws NotFoundHttpException
     * @throws BadRequestHttpException
     * @throws ForbiddenHttpException
     * @throws HttpException
     */
    public function beforeAction($action)
    {
        // 过滤参数空格
        Yii::$app->request->setBodyParams(ArrayHelper::trim(Yii::$app->request->post()));
        Yii::$app->request->setQueryParams(ArrayHelper::trim(Yii::$app->request->get()));

        // 身份验证
        $return = parent::beforeAction($action);

        // 权限验证
        if (!Yii::$app->user->isGuest) {
            // 方法名
            $actionName = $action->id;

            if (!in_array($actionName, $this->optionalLimit)) {
                $route = $action->getUniqueId();
                $member = Yii::$app->user->identity->member;

                // 同一个用户,同一个接口,一段时间内不能多次访问
                /*if (Yii::$app->request->isPost) {
                    $url = CommonHelper::getUrl();
                    $key = 'dengta-'.$member->id.'-'.$url;
                    $lock = Yii::$app->services->commonservice->acquire_global_lock($key);
                    if (empty($lock)) {
                        throw new HttpException(422, '请不要重复点击');
                    }
                }*/

                if (MemberService::checkPermission($member, $route) === false) {
                    throw new HttpException(422, '权限不足.');
                }
            }
        }

        return $return;
    }
}
